import requests
import logging
from typing import Dict, Optional
from app.conf.config import config

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class IPLocationService:
    """
    IP地址地理位置查询服务
    使用ip-api.com提供的免费API
    """
    
    def __init__(self):
        self.api_url = "http://ip-api.com/json/"
        self.headers = {
            "User-Agent": "Shopify-Translation-App/1.0"
        }
    
    def get_location_info(self, ip_address: str) -> Dict:
        """
        获取IP地址的地理位置信息
        
        Args:
            ip_address: IP地址字符串
            
        Returns:
            Dict: 包含地理位置信息的字典
        """
        try:
            # 构建请求URL
            url = f"{self.api_url}{ip_address}"
            
            # 设置代理（如果配置了）
            proxies = {}
            if config.HTTP_PROXY:
                proxies["http"] = config.HTTP_PROXY
            if config.HTTPS_PROXY:
                proxies["https"] = config.HTTPS_PROXY
            
            # 发送请求
            response = requests.get(
                url,
                headers=self.headers,
                proxies=proxies if proxies else None,
                timeout=10
            )
            
            # 检查响应状态
            if response.status_code != 200:
                logging.error(f"IP查询API返回错误状态码: {response.status_code}")
                return {
                    "status": "error",
                    "message": f"API请求失败: {response.status_code}"
                }
            
            # 解析响应数据
            data = response.json()
            
            # 检查查询结果
            if data.get("status") != "success":
                logging.warning(f"IP查询失败: {data.get('message')}")
                return {
                    "status": "error",
                    "message": data.get("message", "Unknown error")
                }
            
            # 返回格式化的地理位置信息
            return {
                "status": "success",
                "ip": ip_address,
                "country": data.get("country", "Unknown"),
                "country_code": data.get("countryCode", "Unknown"),
                "region": data.get("regionName", "Unknown"),
                "city": data.get("city", "Unknown"),
                "latitude": data.get("lat"),
                "longitude": data.get("lon"),
                "timezone": data.get("timezone", "Unknown")
            }
            
        except requests.RequestException as e:
            logging.error(f"IP查询请求异常: {str(e)}")
            return {
                "status": "error",
                "message": f"请求异常: {str(e)}"
            }
        except Exception as e:
            logging.error(f"IP查询处理异常: {str(e)}")
            return {
                "status": "error",
                "message": f"处理异常: {str(e)}"
            }

# 创建服务实例
ip_location_service = IPLocationService()

# 对外提供的函数
def get_ip_location(ip_address: str) -> Dict:
    """
    获取IP地址的地理位置信息
    
    Args:
        ip_address: IP地址字符串
        
    Returns:
        Dict: 包含地理位置信息的字典
    """
    return ip_location_service.get_location_info(ip_address)